// eslint-disable-next-line
import React, { ReactNode, useEffect, useState } from 'react';

import { shallowEqual, useSelector } from 'react-redux';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import { isAdmin } from '@src/components/ability';
import MainNavBar, { MenuTypes } from '@src/components/mainNavBar';
import NotFoundPage from './page/NotFoundPage';
import HomePage from './page/homePage';
import LoginPage from './page/loginPage';
import MainPage from './page/mainPage';
import { createStoreListKey } from './redux/listReducer';
import { AppStore, RecordList, RouteData } from './types';
import componentsMap from './router';
import Layout1 from './components/layout1';
import main from './main';
import AccountPage from './page/accountPage';

const otherComponentList: {
  path: string;
  reg: string;
  component: JSX.Element;
}[] = [];
export default function App() {
  const key = createStoreListKey({ model: 'system', table: 'menu', path: 'getRouters' });
  const routeDataList: RecordList<RouteData> = useSelector((state: AppStore) => state.list[key], shallowEqual);
  const [menuList, setMenuList] = useState<MenuTypes[]>([]);
  useEffect(() => {
    let list: MenuTypes[] = [
      {
        label: '首页',
        key: 'home',
        icon: 'IconHome',
        path: '/home',
        link: '/home',
      },
    ];
    let _isAdmin = isAdmin();
    if (routeDataList?.results?.length) {
      // 循环所有路由，重新组合
      for (let item of routeDataList!.results) {
        // 如果不隐藏
        if (!item.hidden || _isAdmin) {
          // 一级菜单直接打开页面的
          if (item.path === '/' && item.children) {
            for (let sub of item.children) {
              let tmp: MenuTypes = {
                label: sub.meta.title,
                key: sub.path,
                icon: sub.meta.icon,
                path: sub.path,
                link: formatPath('/', sub.path),
                links: [],
                component: sub.component,
              };
              // 有附加页面需要选中一级菜单的
              let otherStartPath = formatPath(`/${sub.path}`);
              otherComponentList.forEach((i) => {
                if (i.reg.includes(otherStartPath)) {
                  tmp.links!.push(i.reg);
                }
              });
              list.push(tmp);
            }
            continue;
          }
          // 一级菜单有二级菜单的
          let data: MenuTypes = {
            label: item.meta.title,
            key: item.path,
            icon: item.meta.icon,
            path: item.path,
            subs: [],
            component: formatPath('/', item.component ?? '').toLowerCase(),
          };
          // 循环所有二级路由
          if (item.children) {
            for (let sub of item.children!) {
              // 如果不隐藏
              if (!sub.hidden) {
                let tmp: MenuTypes = {
                  label: sub.meta.title,
                  key: sub.path,
                  parent: data.key,
                  path: formatPath(sub.path, 'index'),
                  link: formatPath(item.path, sub.path, 'index'),
                  component: formatPath('', sub.component ?? '').toLowerCase(),
                  links: [],
                  isDetail: true, // sub.isDetail === true,
                };
                // 如果需要详情
                if (tmp.isDetail && !sub.path.startsWith('http')) {
                  let detailTmp: MenuTypes = {
                    label: sub.meta.title,
                    key: sub.path,
                    parent: data.key,
                    path: formatPath(sub.path, 'detail/:id'),
                    component: tmp.component?.replace('/index', '/detail').toLowerCase(),
                  };
                  data.subs!.push(detailTmp);
                  // 详情路由也能选中相应的二级菜单
                  tmp.links!.push(formatPath(`/${item.path}/${sub.path}/detail`));
                }
                // 有附加页面需要选中二级菜单和一级菜单的
                let otherStartPath = formatPath(`/${sub.path}/`);
                otherComponentList.forEach((i) => {
                  if (i.reg.includes(otherStartPath)) {
                    tmp.links!.push(i.reg);
                  }
                });
                data.subs!.push(tmp);
              }
            }
          }
          list.push(data);
        }
      }
      setMenuList(list);
    }
  }, [routeDataList]);

  let routes: Array<ReactNode> = menuList.map((item) => {
    if (item.link && item.component) {
      let createEl = componentsMap[item.component || 'any'] || componentsMap['any'];
      return <Route key={item.key} path={item.link} element={createEl(item)} />;
    }
    return (
      <Route key={item.key} path={item.path}>
        {(item.subs || []).map((sub) => {
          let createEl = componentsMap[sub.component || 'any'] || componentsMap['any'];
          return <Route key={sub.key} path={sub.path} element={createEl(sub)} />;
        })}
      </Route>
    );
  });
  let layoutChildren: Array<ReactNode> = [
    <Route key="home" path="home" element={<HomePage />} />,
    <Route key="account" path="account" element={<AccountPage />} />,
  ];
  layoutChildren = layoutChildren.concat(routes);
  layoutChildren = layoutChildren.concat(
    otherComponentList.map((item) => <Route key={item.path} path={item.path} element={item.component} />)
  );
  layoutChildren.push(<Route key="404" path="*" element={<NotFoundPage loading={!routeDataList?.loaded} />} />);

  /// 自定义布局样式 海量的样式
  let layout: ReactNode;
  if (main.layout === 'layout1') {
    layout = createLayout1(layoutChildren, menuList);
  } else {
    layout = createLayout2(layoutChildren, menuList);
  }

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<MainPage />}>
          <Route path="login" index element={<LoginPage />} />
          {layout}
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

function formatPath(...argments: string[]) {
  let hasHttp = '';
  argments.forEach((i) => {
    if (i.startsWith('http')) {
      hasHttp = i;
    }
  });
  if (hasHttp.startsWith('http')) return hasHttp;
  let _p = argments.join('/').replaceAll('//', '/').replaceAll('//', '/');
  return _p;
}

/**
 * -----------------------------------------------
 *      |  二级菜单                         个人菜单
 *  一  |-----------------------------------------
 *  级  |
 *  菜  |   内容
 *  单  |
 *      |
 * -----|
 * 退出 |
 *-------------------------------------------------
 *
 * 一二级菜单分开的样式布局
 * @param layoutChildren 子组件
 * @param menuList 菜单项
 * @returns 布局组件
 */
function createLayout2(layoutChildren: Array<ReactNode>, menuList: Array<MenuTypes>) {
  return (
    <Route path="/" element={<MainNavBar menus={menuList} />}>
      {layoutChildren}
    </Route>
  );
}

/**
 * --------------------------------------------------
 *  logo                                      个人菜单
 * --------------------------------------------------
 *  手   |
 *  风   |
 *  琴   |   内容
 *  菜   |
 *  单   |
 *       |
 * --------------------------------------------------
 * 一二级在一起展开收起的样式
 * @param layoutChildren 子组件
 * @param menuList 菜单项
 * @returns 布局组件
 */
function createLayout1(layoutChildren: Array<ReactNode>, menuList: Array<MenuTypes>) {
  return (
    <Route path="/" element={<Layout1 menus={menuList} />}>
      {layoutChildren}
    </Route>
  );
}
